package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.service.ITimeConfigService;
import net.suncaper.psychological.service.impl.TimeConfigServiceImpl;
import net.suncaper.psychological.model.domain.TimeConfig;
import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.common.utils.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/timeConfig")
public class TimeConfigController {
    
    private final ITimeConfigService timeConfigService = new TimeConfigServiceImpl();
    
    @RequestMapping("/list.do")
    public void list(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TimeConfig> timeConfigs = timeConfigService.getAllTimeConfigs();
            Result.success(timeConfigs).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/listByType.do")
    public void listByType(HttpServletRequest request, HttpServletResponse response) {
        try {
            String configType = request.getParameter("configType");
            if (configType == null || configType.trim().isEmpty()) {
                Result.error("配置类型不能为空").writeTo(response);
                return;
            }
            
            List<TimeConfig> timeConfigs = timeConfigService.getTimeConfigsByType(configType);
            Result.success(timeConfigs).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/getActiveWorkingHours.do")
    public void getActiveWorkingHours(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TimeConfig> timeConfigs = timeConfigService.getActiveWorkingHoursConfigs();
            Result.success(timeConfigs).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取工作时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/getActiveIntervals.do")
    public void getActiveIntervals(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TimeConfig> timeConfigs = timeConfigService.getActiveIntervalConfigs();
            Result.success(timeConfigs).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取间隔配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/get.do")
    public void get(HttpServletRequest request, HttpServletResponse response) {
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                Result.error("ID不能为空").writeTo(response);
                return;
            }
            
            Long id = Long.parseLong(idStr);
            TimeConfig timeConfig = timeConfigService.getTimeConfigById(id);
            
            if (timeConfig == null) {
                Result.error("时间配置不存在").writeTo(response);
                return;
            }
            
            Result.success(timeConfig).writeTo(response);
        } catch (NumberFormatException e) {
            Result.error("ID格式错误").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/add.do")
    public void add(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            TimeConfig timeConfig = JSON.parseObject(jsonData, TimeConfig.class);
            
            if (timeConfig == null) {
                Result.error("时间配置数据不能为空").writeTo(response);
                return;
            }
            
            boolean success = timeConfigService.saveTimeConfig(timeConfig);
            
            if (success) {
                Result.success("添加时间配置成功").writeTo(response);
            } else {
                Result.error("添加时间配置失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("添加时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/update.do")
    public void update(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            TimeConfig timeConfig = JSON.parseObject(jsonData, TimeConfig.class);
            
            if (timeConfig == null || timeConfig.getId() == null) {
                Result.error("时间配置数据或ID不能为空").writeTo(response);
                return;
            }
            
            boolean success = timeConfigService.updateTimeConfig(timeConfig);
            
            if (success) {
                Result.success("更新时间配置成功").writeTo(response);
            } else {
                Result.error("更新时间配置失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("更新时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/delete.do")
    public void delete(HttpServletRequest request, HttpServletResponse response) {
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                Result.error("ID不能为空").writeTo(response);
                return;
            }
            
            Long id = Long.parseLong(idStr);
            boolean success = timeConfigService.deleteTimeConfigById(id);
            
            if (success) {
                Result.success("删除时间配置成功").writeTo(response);
            } else {
                Result.error("删除时间配置失败").writeTo(response);
            }
        } catch (NumberFormatException e) {
            Result.error("ID格式错误").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("删除时间配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/updateStatus.do")
    public void updateStatus(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            List<Long> ids = (List<Long>) data.get("ids");
            Boolean isActive = (Boolean) data.get("isActive");
            
            if (ids == null || ids.isEmpty()) {
                Result.error("ID列表不能为空").writeTo(response);
                return;
            }
            
            boolean success = timeConfigService.updateIsActiveByIds(ids, isActive);
            
            if (success) {
                Result.success("状态更新成功").writeTo(response);
            } else {
                Result.error("状态更新失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("状态更新失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    @RequestMapping("/createDefault.do")
    public void createDefault(HttpServletRequest request, HttpServletResponse response) {
        try {
            timeConfigService.createDefaultTimeConfigs();
            Result.success("默认配置创建成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("创建默认配置失败: " + e.getMessage()).writeTo(response);
        }
    }
    
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
} 